package cn.kvchoi.reactor_nio;

import cn.kvchoi.reactor_nio.server.Reactor;
import cn.kvchoi.reactor_nio.server.handlers.AcceptEventHandler;
import cn.kvchoi.reactor_nio.server.handlers.ReadEventHandler;
import cn.kvchoi.reactor_nio.server.handlers.WriteEventHandler;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;

/**
 * NIO & Reactor pattern (At single thread)
 */
public class ReactorServer {

    static int ASYNC_SERVER_PORT = 4333;

    public static void main(String[] args) {

        try (ServerSocketChannel server = ServerSocketChannel.open()) {
            server.socket().bind(new InetSocketAddress(ASYNC_SERVER_PORT));
            server.configureBlocking(false);
            System.out.println("Server socket bind on port=" + ASYNC_SERVER_PORT + " @ thread=" + Thread.currentThread().getName());

            Reactor reactor = new Reactor();
            reactor.registerChannel(SelectionKey.OP_ACCEPT, server);
            reactor.registerEventHandler(SelectionKey.OP_ACCEPT, new AcceptEventHandler());
            reactor.registerEventHandler(SelectionKey.OP_READ, new ReadEventHandler());
            reactor.registerEventHandler(SelectionKey.OP_WRITE, new WriteEventHandler());

            System.out.println("Reactor run ...");
            reactor.run();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
